﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS_Core_Configuration;
using WCS_Entity.Dto.UpperSysDto;
using WCS_Service.DomianService.Interface;
using WCS_Service.DomianService.Models;
using WCS_Service.Interface;
using WCS_Service.Services;
using WCS_Service.UpperServices;
using WCS_Service.UpperServices.Interfaces;
using WCS_Utility.ConstString;

namespace WCS_Service.DomianService.AutoEquipmentDomain
{
    /// <summary>
    /// 上层系统服务
    /// </summary>
    public class UpperSysDomainService : IUpperSysDomainService
    {
        #region 属性
        private readonly IHttpComDomainService _httpComDomainManage;
        private readonly IUpperSysService _upperSysService;
        private readonly IUpperSysApiService _upperSysApiService;
        private readonly IMapper _mapper;
        private string baseUrl;

        #region 支持的上位服务类型
        private readonly IWMSService _wmsService;
        #endregion

        private ConcurrentDictionary<string, UpperSysModel> sysInfos = new();
        #endregion


        public UpperSysDomainService(IHttpComDomainService httpComDomainManage, 
            IUpperSysService upperSysService, IUpperSysApiService upperSysApiService, 
            IMapper mapper, IWMSService wmsService) 
        {
            _httpComDomainManage = httpComDomainManage;
            _upperSysService = upperSysService;
            _upperSysApiService = upperSysApiService;

            _wmsService = wmsService;

            _mapper = mapper;
            Init();
        }
        private async void Init()
        {
            var upperSys =await _upperSysService.QueryEffectiveUpperSysAsync();
            if (upperSys is not null)
            {
                List<Task> addUpper = new();
                foreach (var upper in upperSys)
                {
                    addUpper.Add(CreatUpperSysInit(upper));
                }
                await Task.WhenAll(addUpper);
            }
        }

        public async Task AbnormalReportAsync(string msg)
        {
            var upperSysInfos = await QueryUpperSysBaseApi(ConstStringData.AbnormalReport_Upper);
            if (upperSysInfos is null || !upperSysInfos.Any())
            {
                Log.Error($"AbnormalReport上报接口没有上位系统支持!"); 
                return;
            }
            return;
        }

        public async Task OrderCompleteReportAsync(string orderId)
        {
            var upperSysInfos = await QueryUpperSysBaseApi(ConstStringData.TaskReport_Upper);
            if (upperSysInfos is null || !upperSysInfos.Any())
            {
                Log.Error($"OrderReport上报接口没有上位系统支持!");
                return;
            }
            return;
        }
        /// <summary>
        /// 异常订单上报
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task OrderAbnormalReportAsync(string orderId, string msg)
        {
            AbnormalInfoModel abnormalInfoModel = new AbnormalInfoModel();
            var url = baseUrl + "";
            var date = JsonConvert.SerializeObject(abnormalInfoModel);
            var result = await _httpComDomainManage.PostAsync(url, date);
            return;
        }

        #region private
        private async Task CreatUpperSysInit(UpperSysDto info)
        {
            UpperSysModel model = new UpperSysModel();
            model.id = info.id;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(ConstStringData.HttpComPara);
            stringBuilder.Append(info.ip);
            stringBuilder.Append(ConstStringData.Colon);
            stringBuilder.Append(info.port);
            model.baseUrl = stringBuilder.ToString();

            var infos = await _upperSysApiService.QueryUppserSysApiBaseIdAsync(info.id);
            if (infos is not null)
            {
                foreach (var item in infos)
                {
                    var apiInfo = _mapper.Map<ApiInfoModel>(item);
                    if (apiInfo is not null)
                    {
                        model.apiInfos.Add(apiInfo);
                    }
                }
            }
            sysInfos.AddOrUpdate(info.upperSys, model, (key, value) => value);
        }
        /// <summary>
        /// 查询支持指定API的上位服务
        /// </summary>
        /// <returns></returns>
        private async Task<List<UpperSysModel>> QueryUpperSysBaseApi(string apiName)
        {
            if (sysInfos is null)
            {
                return null;
            }
            List<Task<UpperSysModel>> addUppserSys = new();
            foreach (var sysInfo in sysInfos)
            {
                if (sysInfo.Value.apiInfos is not null)
                {
                    addUppserSys.Add(TraversalApiInfoAsync(apiName, sysInfo.Value));
                }
            }

            await Task.WhenAll(addUppserSys);
            var accordSys = addUppserSys.Where(a => a.Result is not null)?.Select(a => a.Result)?.ToList();
            return accordSys;
        }
        /// <summary>
        /// 检索上位系统的API是否有指定的API
        /// </summary>
        /// <returns></returns>
        private async Task<UpperSysModel> TraversalApiInfoAsync(string apiName, UpperSysModel info)
        {
            return await Task.Run(() => 
            {
                foreach (var item in info.apiInfos)
                {
                    if (item is not null && item.apiName == apiName)
                    {
                        return info;
                    }
                }
                return null;
            });
        }
        #endregion
    }
}
